import logging
from functools import partial

from rest_framework import viewsets, status, mixins
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet

"""
逻辑删除条件：
    构建module时继承BaseModel
    使用ModelViewSet时替换BaseModelViewSet
    使用GenericViewSet时自定义delete请求需要重写save逻辑，或者注意删除规则是否存在逻辑删除字段
    不使用逻辑删除时继承ModelViewSet即可

"""


# 自定义ModelViewSet
class BaseModelViewSet(mixins.CreateModelMixin,
                       mixins.RetrieveModelMixin,
                       mixins.UpdateModelMixin,
                       mixins.ListModelMixin,
                       GenericViewSet):
    """
       Destroy a model instance.
       """

    # <editor-fold desc="重写删除 -》更新is_del字段">
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        request.data["is_del"] = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_destroy(serializer)

        return Response(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, serializer):
        try:
            serializer.save()
        except Exception as e:
            logging.error("重写删除错误：",e)
    # </editor-fold>
